/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ua.yandex.sumofseries.threads;

/**
 *
 * @author Neophron
 */
public class Sum {

    public static final double STEP = 0.0001;

    public static double sum(int from, int to, int numberOfThreads)
            throws Exception {
        int n = to - from;
        double part = 1.0 * n / numberOfThreads;
        MyThread[] group = new MyThread[numberOfThreads];
        for (int i = 0; i < numberOfThreads; i++) {
            double tfrom = from + part * i;
            double tto = from + part * (i + 1);
            group[i] = new MyThread(tfrom, tto);
            group[i].start();
        }
        boolean needToContinue = true;
        double result = 0;
        while (needToContinue) {
            needToContinue = false;
            for (int i = 0; i < numberOfThreads; i++) {
                if (!group[i].isResultReady()) {
                    needToContinue = true;
                    break;
                }
            }
        }
        for (int i = 0; i < numberOfThreads; i++) {
            result += group[i].getResult();
        }
        return result;
    }

}
